﻿package component.validate.config;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.digester.Digester;
import org.xml.sax.SAXException;

import component.validate.util.PropertiesUtil;

public class ValidatorMap {
	private static ValidatorMap instance = new ValidatorMap();

	private Map validaterMap = new HashMap();

	private ValidatorMap() {
	}

	public static ValidatorMap getInstance() {
		return instance;
	}

	static {
		String[] fileArr = PropertiesUtil.getProperty("validate.files").split(",");
		for(int i=0;i<fileArr.length;i++){
			String uri = fileArr[i];
			Digester digester = new Digester();
			
			digester.push(instance);
			digester.setValidating(false);
			digester.addRuleSet(new ValidatorRuleSet());
			//digester.parse(ValidaterMap.class.getResourceAsStream("validate.xml"));
			try {
				digester.parse(ValidatorMap.class.getResourceAsStream(uri));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	}

	public void addValidatorInfo(ValidatorInfo validaterInfo) {
		this.validaterMap.put(validaterInfo.getId(), validaterInfo);
	}

	public ValidatorInfo getValidatorInfo(String id) {
		return (ValidatorInfo) this.validaterMap.get(id);
	}
	
	private static String getConValue(Object value){
		if(value instanceof String){
			return "'" + value + "'";
		}else{
			return String.valueOf(value);
		}
	}
	
	public static void main(String[] args) {
		ValidatorInfo val = ValidatorMap.getInstance().getValidatorInfo("TFM_GZTF_BASEDATA");
		List deleteValList = val.getDeleteValList();
		List saveValList = val.getSaveValList();
		DeleteValidatorInfo delVal = (DeleteValidatorInfo)deleteValList.get(0);
		SaveValidatorInfo saveVal = (SaveValidatorInfo)saveValList.get(0);
		
		System.out.println(val.getTable() + "," + delVal.getTable() + "," + saveVal.getValFields());
		System.out.println(val.getSaveValSql(null));
		
		Object[] conVals = new Object[]{"wrwr"};
		String sql = val.getSaveValSql(null)[0];
		if(conVals!=null){
			for(int i=0;i<conVals.length;i++){
				sql = sql.replaceAll(":"+(i+1),getConValue(conVals[i]));
			}
		}
		System.out.println("sql = " + sql);
	}

}
